package net.acoinWork.dynRender.render;


import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * 渲染器,使用FreeMarker引擎(敬请期待|-_-|)
 *
 * @author xusk
 * @Date: 15/12/31 下午2:41
 */
public enum FreeMarkerRenderer implements Renderer<Map> {
    INSTANCE;
    private static Configuration cfg;
    private static final StringTemplateLoader templateLoader = new StringTemplateLoader();

    static {
        cfg = new Configuration();
        cfg.setDefaultEncoding("utf-8");
        cfg.setTemplateLoader(templateLoader);
    }

    @Override
    public String render(String preRender, Map map) {
        String result = "<null>";
        StringWriter out = new StringWriter();
        try {
            Object templateSource = templateLoader.findTemplateSource(preRender);
            if (templateSource == null) {
                templateLoader.putTemplate(preRender, preRender);
            }
            Template template = cfg.getTemplate(preRender);
            template.process(map, out);
            result = out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public void loadLib(String libContent) {
        templateLoader.putTemplate("lib", libContent);
        cfg.addAutoInclude("lib");
    }


}
